<template>
	<view>
		<view class="page page-bottom-bar newPrescript">
			<!-- 患者信息 -->
			<view class="part1 box-shadow">
				<view class="font13 font-969696 flex-row-between">
					<view>NO:{{familyInfo.code||''}}</view>
				</view>
				<view class="hospital font15 font-b tc">{{userInfo.doctor_info?(userInfo.doctor_info.hospital_name||''):''}}处方</view>
				<view class="item flex-row-start">
					<view>患者姓名</view>
					<input class="flex-1" type="text" disabled :value="form.name" @input="Onname" placeholder="请输入患者姓名" />
				</view>
				<view class="item flex-row-start">
					<view>患者年龄</view>
					<input class="flex-1" type="text" disabled :value="form.age" @input="Onage" placeholder="请输入患者年龄" />
				</view>
				<view class="item nob flex-row-start">
					<view>患者性别</view>
					<uni-data-checkbox class="sex flex-1"
						disabled
						v-model="form.gender"
						:localdata="gender.range"
						selectedColor="#6bcbb6"
						selectedTextColor="#1e1e1e"
						@change="Onsex">
					</uni-data-checkbox>
				</view>
			</view>
			<!-- 诊断信息 -->
			<view class="part2 box-shadow">
				<view class="font14">诊断</view>
				<textarea :value="form.content" @input="Ontextarea" placeholder="请输入诊断结果" placeholder-class="placeholderClass"></textarea>
			</view>
			<!-- 药品信息 -->
			<view class="part3 box-shadow">
				<view class="prescript-list drugs-box">
					<view style="font-size: 26rpx;" v-if="businessobj.id">
						药房：{{businessobj.name}}
						<text @click="goNext('/pagesB/business/businessSelect')" style="color: #6bcbb6;padding: 10rpx;margin-left: 10rpx;">更换</text>
					</view>
					<block v-for="(item, index) in drugs" :key="index">
						<view class="item">
							<view class="part2">
								<view class="name font14">{{item.name}} *{{item.number}}</view>
								<view class="font12 font-969696">用法用量：{{item.frequency}}，{{item.consumption}}，{{item.usage}}</view>
							</view>
							<view class="part3 flex-row-end">
								<view class="btn-small grey" @click="del(item.id)">删除</view>
								<view class="btn-small green" @click="goNext('/pagesA/prescript/drugsEdit?mode=edit&id=' + item.id)">编辑用量</view>
							</view>
						</view>
					</block>
				</view>
				<view class="btn font14 tc" v-if="businessobj.id" @click="goNext('/pagesA/prescript/drugsList?business_id='+businessobj.id)">+ 新增药品</view>
				<view class="btn font14 tc" v-else @click="goNext('/pagesB/business/businessSelect')">选择药房</view>
			</view>
		</view>
		<!-- 按钮 -->
		<view class="fix-bottom-btn flex-row-center">
			<view class="btn flex-row-center font-ffffff font15" @click="send">保存</view>
		</view>
		<!-- 弹窗-处方名称 -->
		<uni-popup ref="name" type="center">
			<view class="popup-name">
				<view class="font15 tc font-b">处方名称</view>
				<view class="f-input">
					<input class="flex-1" type="text" :value="title" @input="Ontitle" placeholder="请输入处方名称" />
				</view>
				<view class="flex-row-between">
					<view class="btn btn1" @click="closeName">取消</view>
					<view class="btn btn2" @click="save">保存</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import Compicker from '@/components/Compicker.vue'
	import topBar from "@/components/ComTopBar.vue";
	export default {
		components: { Compicker, topBar },
		data() {
			return {
				prescriptId: '', // 处方id
				chatId: '', // 聊天记录id

				// 性别
				gender: {
					value: '1',
					range: [
						{ value: '1', text: "男" },
						{ value: '2', text: "女" }
					]
				},
				form: {
					name: '',
					age: '',
					gender: '1',
					content: ''
				},
				title: '', // 处方名称
				drugs: [], // 药品列表
				
				businessobj: {},
				familyInfo: {},
			}
		},
		onLoad(options) {
			this.prescriptId = options.prescriptId
			this.chatId = options.chatId

			// 获取用户信息
			this.$Http({
				url: 'getUserInfo',
				type: 'POST',
				data: {}
			}).then(res => {
				this.userInfo = res.data
			})

			// 处方详情
			this.$Http({
				url: 'detailsPrescription',
				data: {doctor_prescription_id: options.prescriptId}
			}).then(res => {
				if (res.code == 1) {
					let arr = []
					
					// 就诊人详情
					this.familyInfo = res.data.user_the_patient_info
					this.form.name = res.data.user_the_patient_info.name
					this.form.gender = res.data.user_the_patient_info.sex
					this.form.age = this.$base.Onage(res.data.user_the_patient_info.birthday)

					this.form.content = res.data.diagnose
					if(res.data.business_info){
						if(res.data.business_info){
							this.$store.commit('selectBusinessobj', res.data.business_info)
							this.businessobj = res.data.business_info
						}
						this.businessobj = res.data.business_info
					}
					res.data.doctor_prescription_access.forEach(item => {
						arr.push({
							id: item.goods_id,
							name: item.goods_name,
							number: item.number,
							usage: item.usages,
							consumption: item.consumptions,
							frequency: item.frequencys,
							remark: item.remark
						})
					})

					this.drugs = arr
					uni.setStorage({
						key: 'drugs',
						data: JSON.stringify(this.drugs)
					});
				} else {
					uni.showToast({ title: res.msg, icon: 'none' })
				}
			})
		},
		onUnload(){
			this.$store.commit('selectBusinessobj', {})
		},
		onShow() {
			// 从缓存中拿取药品列表信息
			let $drugs = uni.getStorageSync("drugs")
			this.drugs = $drugs ? JSON.parse($drugs) : []
			
			var businessobj = this.$store.state.businessobj
			if(!this.businessobj.id || !businessobj.id || this.businessobj.id!=businessobj.id){
				this.drugs = []
				uni.removeStorageSync("drugs")
			}
			this.businessobj = businessobj
		},
		methods: {
			Ontitle(e) {
				this.title = e.detail.value
			},
			Onname(e) {
				this.form.name = e.detail.value
			},
			Onage(e) {
				this.form.age = e.detail.value
			},
			Onsex(e){
				this.form.gender = e.detail.value
			},
			Ontextarea(e) {
				this.form.content = e.detail.value
			},
			// 删除药品
			del (id) {
				let that = this
				uni.showModal({
					title: '提示',
					confirmText: '确认',
					confirmColor: '#b8875c',
					cancelText: '取消',
					content: '您确定要删除该药品吗?',
					success: function(res) {
						if (res.confirm) {
							that.drugs.forEach((item, i) => {
								if (item.id == id) {
									that.drugs.splice(i ,1);
									uni.setStorage({
										key: 'drugs',
										data: JSON.stringify(that.drugs)
									});
								}
							})
						}
					}
				});
			},
			// 打开处方名称
			openName () {
				if (this.form.content == '') {
					uni.showToast({ title: '请输入诊断内容', icon: 'none' })
					return false
				}
				this.$refs.name.open()
			},
			// 关闭处方名称
			closeName () {
				this.$refs.name.close()
			},
			// 保存为常用处方
			save () {
				if (this.title == '') {
					uni.showToast({ title: '请输入处方名称', icon: 'none' })
					return false
				}

				let goods_ids = [],usages = [],consumptions = [],frequencys = [], remark = [], number = [];
				this.drugs.forEach((item, i) => {
					goods_ids.push(item.id)
					usages.push(item.usage)
					consumptions.push(item.consumption)
					frequencys.push(item.frequency)
					remark.push(item.remark)
					number.push(item.number)
				})
				let obj = {
					business_id: this.businessobj.id || 0,
					name: this.title,
					diagnosis: this.form.content,
					goods_ids: goods_ids.join(','),
					usages: usages.join(','),
					consumptions: consumptions.join(','),
					frequencys: frequencys.join(','),
					remark: remark.join(','),
					number: number.join(',')
				}

				this.$Http({
					url: 'addCommonlyUsedPrescription',
					type: 'POST',
					token: true,
					data: obj
				}).then(res => {
					if (res.code == 1) {
						this.$refs.name.close();
						uni.showToast({ title: '保存成功' })
						uni.removeStorage({ key: 'drugs' });
					} else {
						uni.showToast({ title: res.msg, icon: 'none' })
					}
				})
			},
			// 发送处方
			send () {
				var that = this
				if (this.form.content == '') {
					uni.showToast({ title: '请输入诊断内容', icon: 'none' })
					return false
				}

				let goods_ids = [],usages = [],consumptions = [],frequencys = [], remark = [], number = [];
				this.drugs.forEach((item, i) => {
					goods_ids.push(item.id)
					usages.push(item.usage)
					consumptions.push(item.consumption)
					frequencys.push(item.frequency)
					remark.push(item.remark)
					number.push(item.number)
				})
				
				let obj = {
					doctor_prescription_id: this.prescriptId || 0,
					chat_id: this.chatId || 0,
					business_id: this.businessobj.id || 0,
					diagnose: this.form.content,
					goods_ids: goods_ids.join(','),
					usages: usages.join(','),
					consumptions: consumptions.join(','),
					frequencys: frequencys.join(','),
					remark: remark.join(','),
					number: number.join(','),
				}
				
				this.$Http({
					url: 'doctorEditPrescription',
					type: 'POST',
					token: true,
					data: obj
				}).then(res => {
					if (res.code == 1) {
						uni.showToast({ title: '保存处方成功' })
						uni.removeStorage({ key: 'drugs' });
						setTimeout(()=>{
							uni.navigateBack();
						}, 2000)
					} else {
						uni.showToast({ title: res.msg, icon: 'none' })
					}
				})
			},
			// 跳转
			goNext (url) {
				uni.navigateTo({
					url: url
				})
			}
		}
	}
</script>

<style lang="less">
	@import url("style.less");
	
	/deep/.u-navbar__content__right__text{
		color: #006EFF;
	}
</style>
